trigger PA_Update_Percentage_Trigger on Productivity_Allocations__c (before update) {
    String errmsg = '';
    Boolean isError = false;

    Productivity_Allocations__c NewPA = Trigger.new[0];
    Productivity_Allocations__c OldPA = Trigger.old[0];

    Decimal Percent3 = 0.00;
    if(OldPA.Allocation_Percentage__c== null){
        Percent3 = NewPA.Allocation_Percentage__c;
    }
    else
    {
        Percent3 = NewPA.Allocation_Percentage__c - OldPA.Allocation_Percentage__c;
    }   
            
    Opportunity RelatedOp = [Select Id, Opportunity_Percentage_Allocated__c, OwnerId, (select id, Sales_Associate__c from Productivity_Allocations__r order by createddate limit 1) from Opportunity where Id =: NewPA.Opportunity_Name__c Limit 1];
    Percent3 = Percent3 + RelatedOp.Opportunity_Percentage_Allocated__c;
    if (Percent3 > 100.00)
    {
        errmsg += 'Total Productivity Allocation percent is currently '+Percent3+'% The Total Allocation percentage cannot be greater than 100%';
        isError = true;
        NewPA.addError(errmsg);
    }
    
    
    for(Productivity_Allocations__c pa:Trigger.new)
    {
        if(relatedOp.Productivity_Allocations__r.size() > 0)
        {
           if(pa.id == relatedOp.Productivity_Allocations__r[0].id && pa.Sales_Associate__c != relatedOp.ownerid)
           {
               pa.addError('The Sales Associate for the first Productivity Allocation record cannot be changed. This PA record is reserved for the Opportunity Owner.');
           }
        }    
    
    }
        
}